<template>
	<view class="page">
		<!-- <c-nav-bar :title="titleHeader" ></c-nav-bar> -->
		<view class="upload">
			<u-upload :fileList="fileList" multiple :maxCount="9" :maxSize="10 * 1024 * 1024" @afterRead="afterRead"
				@delete="deletePic" @oversize="overSize">
				<image class="upload-image"
					src="https://i.ringzle.com/file/20231114/53102e3179d84a17ab47d8df72923ef7.png" mode=""></image>
			</u-upload>
		</view>
		<view class="title">
			<input type="text" class="input" v-model="dto.title" maxlength='20' placeholder="填写标题" />
		</view>
		<view class="text-text">
				<u--textarea class="u-text" v-model="dto.content" confirmType="return" maxlength='-1' placeholder="请输入内容"
					autoHeight border="bottom"></u--textarea>
		</view>
		<view class="address" @click="getLocation()">
			<view class="left">
				<image src="https://i.ringzle.com/file/20231114/c07536a73bb142f980d3be3f208cfa8a.png" mode=""></image>
				<text>当前位置</text>
			</view>
			<view class="rightdiv">
				<view class="rightdiv1">
					{{address}}
				</view>
				<view class="rightdiv2">
					<u-icon name="arrow-right"></u-icon>
				</view>
				
			</view>
		</view>
	<!-- 	<view class="agree">
			<image src="@/static/index/steamerTicket/icon_not_selected.png" v-if="!agree" @tap="agree=!agree">
			</image>
			<image src="@/static/index/steamerTicket/icon_selected.png" v-else @tap="agree=!agree">
			</image>
			<text>同意</text>
			<text @tap="showXy">《攻略游记发布规则》</text>
		</view> -->
		<!-- 发布规则 -->
		<u-modal :show="showAgree" :title="title" :content='content' confirmText='同意' confirmColor='#0cbffd'
			@confirm="confirm"></u-modal>
		<view class="btn">
			<view class="btn-left" @click="del">
				取消
			</view>
			<view class="btn-right" @click="save">
				发布
			</view>
		</view>
		<!-- 授权手机登录 -->
		<GetPhoneNumber ref="phoneNumber" @loginSuccess="loginSuccess"></GetPhoneNumber>
	</view>

</template>

<script>
	var amapFile = require('../../utils/amap-wx.130.js');
	import GetPhoneNumber from '@/compoments/Getphonenumber/index.vue'
	export default {
		components: {
			GetPhoneNumber,
		},
		data() {
			return {
				titleHeader:'打卡',
			address:'',
				fanwei:false,
				jingdu:'',
				weidu:'',
				mapdata:{},
				fileList: [],
				value1: '',
				value: '',
				codeImg: [],
				agree: false,
				picList: [],
				dto: {
					attractionName:'',//景点名称
					imageList: '', //	图片
					publisherType: 1, //发布者类型 0官方 1用户
					title: '', //	标题
					content: '', //	攻略内容,
					latitude: '',  //纬度
					longitude: '',//经度
					realName: '', //用户名
					userId: '',  //用户ID
				},
				title: '发布规则',
				content: '发布规则发布规则发布规则发布规则发布规则发布规则',
				showAgree: false,
				imgArr: [],
			}
		},
		onLoad(option) {
			this.mapdata={
				latitude:Number(option.lat),
				longitude:Number(option.lng),
				name:option.name,
			}
			this.dto.latitude =Number(option.lat);
			this.dto.longitude = Number(option.lng);
			this.getLocation();
		},
		methods: {
			getLocation() {
				var myAmapFun = new amapFile.AMapWX({
					key: '4250d90eec4a2bcaaf9c4f486d2ad623'
				});
				let that = this;
				myAmapFun.getRegeo({
					success: function(data) {
						  console.log('111111111111111111', data[0].name)
						
						that.address = data[0].name;
					}
				})
				
				
				uni.getLocation({
					type: 'wgs84', //设置type为gcj02
					isHighAccuracy: true,
					success: async (res) => {
						console.log(res);
						const {
							latitude,
							longitude
						} = res
						
						//this.$showToast("已获取当前位置");
						//this.dto.latitude = latitude
						//this.dto.longitude = longitude
						that.jingdu= latitude;
						that.weidu= longitude;
						//this.fanwei
						// this.dto.latitude 
						// this.dto.longitude 
								var lng1 =longitude;
						        var lat1 = latitude;
								
						        var lng2 = that.dto.longitude; 
						        var lat2 =that.dto.latitude;
							
								
								// var lng2 =117.249533;
								// var lat2 =31.887308;
								//    console.log('111111111111111111',lng1,lat1,lng2,lat2)								
								// function deg2rad(deg) {
								//     return deg * (Math.PI / 180);
								// }
								// function calculateDistance(lat1, lon1, lat2, lon2) {
								//     const R = 6371; // 地球半径，单位为千米
								//     const dLat = deg2rad(lat2 - lat1);
								//     const dLon = deg2rad(lon2 - lon1);
								
								//     const a =
								//         Math.sin(dLat / 2) * Math.sin(dLat / 2) +
								//         Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
								//         Math.sin(dLon / 2) * Math.sin(dLon/ 2);
								
								//     const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
								//     const distance = R * c; // 距离，单位为千米
								//     return distance;
								// }							 
								// // 示例经纬度：纽约市和洛杉矶的经纬度
								// const lat11 =30.72573; // 纽约市纬度
								// const lon11 = 122.45137; // 纽约市经度
								// const lat22 =31.887308; // 洛杉矶纬度
								// const lon22 = 117.249533 ; // 洛杉矶经度
								
								// const distance = calculateDistance(lat11, lon11, lat22, lon22);
								// console.log('输出结果',distance); // 输出结果：3946.27 
								 
								 
						        var radLat1 = lat1*Math.PI / 180.0;
						        var radLat2 = lat2*Math.PI / 180.0;
						        var a = radLat1 - radLat2;
						        var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
						        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
						          Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
						        s = s *6378.137 ;// EARTH_RADIUS;
						        s = Math.round(s * 10000) / 10000;
						        s = s * 1000
						        if (isNaN(s)) {
						          return 0;
						        }
								  console.log('ssssssssssssssssssss',s)
						        if (s > 2000) {
						          //    大于10000米时
						          that.fanwei=false; 
								  
						        } else {
								  that.fanwei=true;
						        }
						       		
					},
					fail: function(err) {
						console.log("?? ~ file: clockIn.vue:72 ~ getLocation ~ err:", err)
					},
					complete: function() {
						console.log('complete')
					}
				})

			},
			// 取消发布
			del() {
				this.dto = {}
				this.agree = false
				this.fileList = []
				this.$showToast("取消成功");
				wx.navigateTo({
				   url: '/pages/touristMap/index'
				 }) 
			},
			// 确定发布
			save() {
				//this.dto.userId = JSON.parse(wx.getStorageSync('userInfo')).id 
			//	console.log(typeof(this.dto.userId));
				if(this.jingdu==''){
					this.$showToast("请先点击定位获取经纬度");
				}
				else if( this.fanwei==false){
						this.$showToast("您不在打卡范围之内,请前往打卡地");
				}
				else{
					this.$login().then(res => {
						if (res === 0) {
							this.dto.realName = JSON.parse(wx.getStorageSync('userInfo')).realName;
							this.dto.userId = JSON.parse(wx.getStorageSync('userInfo')).id;
							//console.log(this.dto);
							if (!this.dto.imageList) return this.$showToast("请添图片或视频");
							if (!this.dto.title) return this.$showToast("请填写标题");
							if (!this.dto.content) return this.$showToast("请填写内容");
						//	if (!this.agree) return this.$showToast('请选择预订协议');	
							
							this.dto.attractionName=this.mapdata.name;
						
							this.$api.post('/api/wisdom/savepictureData', this.dto).then(res => {
								
								if (res.data.code == 0) {
									this.$showToast("发布成功");
									this.dto = {};
									this.agree = false;
									this.fileList = [];
									this.mapdata={};
									setTimeout(() => {
										uni.navigateBack({
											delta: 1
										});
									}, 1000);
							
								} else if (res.data.code == 500) {
									this.$showModal(res.data.msg);
								}
							
							})
							
						} else {
							this.$refs['phoneNumber'].show = true;
						}
					})
					
				}
			},

			// 协议
			showXy() {
				this.showAgree = true
			},
			// 已知晓
			confirm() {
				this.agree = true
				this.showAgree = false
			},



			// 图片大小超出最大允许大小
			overSize(e) {
				uni.$u.toast('上传图片大小不能超过10MB!')
			},



			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},


			// 新增图片
			async afterRead(event) {
				console.log(event, '这是什么');
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let Lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				Lists.map((item) => {
					console.log(item.url, '----00000----');
					this.picList.push(
						item.url,
					)
				})

				for (let i = 0; i < Lists.length; i++) {
					const result = await this.uploadFilePromise(Lists[i].url)

					this.imgArr.push(result)
				}
				this.dto.imageList = this.imgArr;

			},

			//上传图片
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						//url: this.$common.domain+'/api/common/upload', // 仅为示例，非真实的接口地址
						url: 'https://i.ringzle.com/island-cloud-server/oss/file/aliyunUpload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',

						header: {
							token: wx.getStorageSync('access_token')
						},
						success: (res) => {
							console.log(res, '结果是什么');
							let data = JSON.parse(res.data) //最终传给的是字符串，这里需要转换格式
							console.log(data, '出来了？？');

							this.fileList.push({
								url: data.data.url
							})
							console.log(data.data.url, '看看路径');


							resolve(data.data.url)
						}
					});
					console.log(a, '3333');
				})
			},

			// ?access_token=b0f3fa51-2ce0-4141-8c1f-2e90aebaca1


		}
	}
</script>

<style lang="less">
	.title {
		.input {
			margin: 30rpx 0;
			border-bottom: 0.5rpx solid #EFEFEF;
			padding-bottom: 30rpx;
			font-size: 30rpx !important;
			color: #111 !important;
		}
	}
.rightdiv{
	display: flex;
	align-items: center;
}


	.address {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin: 40rpx 0;

		.left {
			display: flex;

			image {
				width: 36rpx;
				height: 36rpx;

			}

			text {
				font-size: 28rpx;
				color: #333333;
				margin: 0 16rpx;

			}
		}
	}

	.agree {
		box-sizing: border-box;
		// margin: 24rpx 36rpx;
		display: flex;
		align-items: center;
		// padding: 51rpx 0 51rpx;

		image {
			width: 32rpx;
			height: 32rpx;
			margin-right: 16rpx;

		}

		text {
			font-size: 26rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #666666;
		}

		text:nth-child(3) {
			color: #007A69;
			margin-left: 10rpx;
		}
	}

	.btn {
		display: flex;

		justify-content: space-between;
		align-items: center;
		text-align: center;
		margin: 60rpx 0;

		.btn-left {
			width: 200rpx;
			height: 88rpx;
			border-radius: 50rpx;
			border: 1rpx solid #CCCCCC;
			font-size: 32rpx;
			color: #999999;
			display: flex;
			justify-content: center;
			line-height: 88rpx;
		}

		.btn-right {
			line-height: 88rpx;
			width: 424rpx;
			height: 88rpx;
			border-radius: 50rpx;
			border: 1rpx;
			background-color: #0EBFFE;
			font-size: 32rpx;
			color: #FFFFFF;
			display: flex;
			justify-content: center;

		}
	}
	.page {
		box-sizing: border-box;
		padding: 48rpx 32rpx;
		// height: 100vh;
		width: 100vw;
		// padding-top: 150rpx;
	}
	
	.upload {
		// width: 210rpx !important;
		// height: 210rpx !important;
	
		.upload-image {
			width: 210rpx !important;
			height: 210rpx !important;
			margin: 8rpx !important;
		}
	}
	
	.u-upload__button {
		width: 210rpx !important;
		height: 210rpx !important;
	}
	
	.u-upload__wrap__preview__image {
		width: 210rpx !important;
		height: 210rpx !important;
	}
	
	.u-upload__wrap__preview {
		margin: 8rpx !important;
	}
	
	.u-textarea {
		padding: 0 !important;
		border: 0 !important;
		border-radius: 0 !important;
	
	}
	
	.u-textarea__field {
		height: 35vh !important;
		border-bottom: 0.5rpx solid #EFEFEF !important;
		padding-bottom: 30rpx !important;
		font-size: 28rpx !important;
		color: #111 !important;
		padding-bottom: 20rpx !important;
	}
	
	.u-icon__icon {
		font-size: 24rpx !important;
		line-height: 24rpx !important;
	}
</style>
